package com.alibaba.config;

import com.alibaba.model.entity.Goods;
import com.alibaba.service.GoodsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.redisson.api.RBloomFilter;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * @author ZhouYaDong
 * @date 2025/9/28
 * @description
 */
@Slf4j
@Component
public class BloomFilterInitializer implements ApplicationRunner {

    @Resource
    private GoodsService goodsService;

    @Resource
    private RBloomFilter<String> goodsBloomFilter;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    // Redis Set Key，用于调试和维护 BloomFilter 中的 ID
    private static final String BLOOM_SET_KEY = "goods:bloom:set";

    @Override
    public void run(ApplicationArguments args) {
        try {
            // 1. 获取最新有效商品 ID 列表
            val goods = goodsService.listAvailableGoods();
            List<Long> validGoodsIds = goods.stream().map(Goods::getId).toList();
            log.info("[BloomFilterInitializer] Fetched {} available goods from database", validGoodsIds.size());
            if (validGoodsIds.isEmpty()) {
                log.warn("[BloomFilterInitializer] No available goods to initialize Bloom filter");
                return;
            }

            // 2. 清空已有布隆过滤器（如果需要完全更新）
            // 注意：Redisson 的 BloomFilter 不支持直接清空，需要删除再重建
            if (goodsBloomFilter.isExists()) {
                goodsBloomFilter.delete();
                log.info("[BloomFilterInitializer] Existing Bloom filter deleted for refresh");
            }

            // 3. 初始化布隆过滤器容量和误判率
            // 假设总商品量 100_000，误判率 0.01
            goodsBloomFilter.tryInit(100_000L, 0.01);

            // 4. 清空 Redis Set
            redisTemplate.delete(BLOOM_SET_KEY);
            log.info("[BloomFilterInitializer] Existing Redis Set deleted for refresh");

            // 5. 写入最新商品 ID
            validGoodsIds.forEach(id -> {
                String idStr = String.valueOf(id);
                goodsBloomFilter.add(idStr);
                redisTemplate.opsForSet().add(BLOOM_SET_KEY, idStr);
            });
            log.info("[BloomFilterInitializer] Bloom filter and Redis Set initialized with {} goods IDs", validGoodsIds.size());

        } catch (Exception e) {
            log.error("[BloomFilterInitializer] Failed to initialize Bloom filter and Redis Set", e);
        }
    }
}
